#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>

#include <linux/i2c-dev.h>
#include <sys/ioctl.h>

#include <pthread.h>

#include "i2clang.h"
#include "plugins.h"

#define I2C_MAX_BUF 8096

int open_i2c_bus( uint8_t );
int set_i2c_addr( int, uint8_t );
int close_i2c_bus( int );
int print_data( uint8_t*, uint16_t );

int main( int argc, char **argv )
{
	int ret;
	int fd=-1;
	int i=0;
	int bus=-1;
	int addr=-1;
	uint8_t *buf=NULL;
	op *ops = i2clang( argc, argv );
	if ( ops == NULL )
	{
		printf("No commands nothing to do\n");
		return 1;
	}

	i=0;
	while ( ops[i].op != OP_NONE )
	{
		switch ( ops[i].op )
		{
			//---------------------------------------------------------
			case OP_WRITE:
				ret = write( fd, ops[i].data, ops[i].size );
				if ( ret != ops[i].size )
				{
					printf("Writen %d of %d bytes \n", ret, ops[i].size );
				}
				break;
			
			//---------------------------------------------------------
			case OP_READ:
				buf = malloc( sizeof(uint8_t)*ops[i].size );
				ret = read( fd, buf, ops[i].size );
				if ( ret != ops[i].size )
				{
					printf( "Read %d of %d\n", ret, ops[i].size );
					print_data( buf, ret );
				}
				free( buf );
				break;
			
			//---------------------------------------------------------
			case OP_READALL:
				buf = malloc( sizeof(uint8_t)*I2C_MAX_BUF );
				ret = read( fd, buf, I2C_MAX_BUF );
				if ( ret > 0 )
				{
					printf("Read %d bytes\n", ret);
					print_data( buf, ret );
				}
				free( buf );
				break;
			
			//---------------------------------------------------------
			case OP_ADDR:
				addr = ops[i].val;
				set_i2c_addr( fd, addr );
				break;
			
			//---------------------------------------------------------
			case OP_BUS:
				bus = ops[i].val;
				open_i2c_bus( bus );
				break;
			
			//---------------------------------------------------------
			default:
				break;
		}
		i++;
	}
	
	i = 0;
	while ( ops[i].op != OP_NONE )
	{
		if ( ops[i].size != 0 )
			free( ops[i].data );
		i++;
	}
	free( ops );

	return 0;
}


//open i2c bus
int open_i2c_bus( uint8_t bus )
{
	int fd=-1;
	const int buf_size = 16;
	char fname[buf_size]; memset( fname, 0, buf_size );

	snprintf( fname, buf_size, "i2c-%d", bus );
	fd = open( fname, O_RDWR );
	if ( fd < 0 )
	{
		printf("Cannot open %s bus\n", fname);
		return -1;
	}
	return fd;
}


//choose current i2c bus used address
int set_i2c_addr( int fd, uint8_t addr )
{

	if ( ioctl( fd, I2C_SLAVE, (int)addr ) < 0 )
	{
		printf("Cannot setupd address %d on bus\n",addr);
		return -1;
	}

	return 0;
}


//close i2c fd
int close_i2c_buf( int fd )
{
	close( fd );
	return 0;
}

int print_data( uint8_t *p, uint16_t s )
{
	return 0;
}

